package com.tianjs.current.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 共享式锁
 * 同一时间，可以有多个线程获取到锁
 * @author admin
 *
 */
public class TwinsLock implements Lock {
	//将操作代理到sync
	private final Sync sync = new Sync(2);
	
	//静态内部类，自定义同步器,继承队列同步器
	private static class Sync extends AbstractQueuedSynchronizer{
		private static final long serialVersionUID = 230871948385115376L;
		Sync(int count){
			if(count<0) {
				throw new IllegalArgumentException("count必须大于0");
			}
			setState(count);
		}
		//获取同步状态
		public int tryAcquireShared(int reduceCount) {
			for(;;) {//死循环获取同步状态
				System.out.println(Thread.currentThread().getName());
				int current = getState();
				int newCount = current - reduceCount;
				if(newCount<0||compareAndSetState(current, newCount)) {
					return newCount;
				}
					
			}
		}
		//释放同步状态
		public boolean tryReleaseShared(int returnCount) {
			for(;;) {//死循环获取同步状态
				int current = getState();
				int newCount = current + returnCount;
				if(compareAndSetState(current, newCount)) {
					return true;
				}
					
			}
		}
	}

	@Override
	public void lock() {
		sync.acquireShared(1);
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {

	}

	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void unlock() {
		sync.releaseShared(1);
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
